1   /*
2    * Copyright (C) 2007 The Guava Authors
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    * http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package com.google.common.collect;
18  
19  import static com.google.common.base.Preconditions.checkArgument;
20  import static com.google.common.base.Preconditions.checkNotNull;
21  import static com.google.common.base.Preconditions.checkState;
22  import static com.google.common.base.Predicates.equalTo;
23  import static com.google.common.base.Predicates.in;
24  import static com.google.common.base.Predicates.not;
25  import static com.google.common.collect.CollectPreconditions.checkRemove;
26  
27  import com.google.common.annotations.Beta;
28  import com.google.common.annotations.GwtCompatible;
29  import com.google.common.base.Function;
30  import com.google.common.base.Objects;
31  import com.google.common.base.Optional;
32  import com.google.common.base.Preconditions;
33  import com.google.common.base.Predicate;
34  
35  import java.util.Arrays;
36  import java.util.Collection;
37  import java.util.Collections;
38  import java.util.Comparator;
39  import java.util.Enumeration;
40  import java.util.Iterator;
41  import java.util.List;
42  import java.util.ListIterator;
43  import java.util.NoSuchElementException;
44  import java.util.PriorityQueue;
45  import java.util.Queue;
46  
47  import javax.annotation.Nullable;
48  
49  /**
50   * This class contains static utility methods that operate on or return objects
51   * of type {@link Iterator}. Except as noted, each method has a corresponding
52   * {@link Iterable}-based method in the {@link Iterables} class.
53   *
54   * <p><i>Performance notes:</i> Unless otherwise noted, all of the iterators
55   * produced in this class are <i>lazy</i>, which means that they only advance
56   * the backing iteration when absolutely necessary.
57   *
58   * <p>See the Guava User Guide section on <a href=
59   * "http://code.google.com/p/guava-libraries/wiki/CollectionUtilitiesExplained#Iterables">
60   * {@code Iterators}</a>.
61   *
62   * @author Kevin Bourrillion
63   * @author Jared Levy
64   * @since 2.0 (imported from Google Collections Library)
65   */
66  @GwtCompatible(emulated = true)
67  public final class Iterators {
68    private Iterators() {}
69  
70    static final UnmodifiableListIterator<Object> EMPTY_LIST_ITERATOR
71        = new UnmodifiableListIterator<Object>() {
72          @Override
73          public boolean hasNext() {
74            return false;
75          }
76          @Override
77          public Object next() {
78            throw new NoSuchElementException();
79          }
80          @Override
81          public boolean hasPrevious() {
82            return false;
83          }
84          @Override
85          public Object previous() {
86            throw new NoSuchElementException();
87          }
88          @Override
89          public int nextIndex() {
90            return 0;
91          }
92          @Override
93          public int previousIndex() {
94            return -1;
95          }
96        };
97  
98    /**
99     * Returns the empty iterator.
100    *
101    * <p>The {@link Iterable} equivalent of this method is {@link
102    * ImmutableSet#of()}.
103    *
104    * @deprecated Use {@code ImmutableSet.<T>of().iterator()} instead; or for
105    *     Java 7 or later, {@link Collections#emptyIterator}. This method is
106    *     scheduled for removal in May 2016.
107    */
108   @Deprecated
109   public static <T> UnmodifiableIterator<T> emptyIterator() {
110     return emptyListIterator();
111   }
112 
113   /**
114    * Returns the empty iterator.
115    *
116    * <p>The {@link Iterable} equivalent of this method is {@link
117    * ImmutableSet#of()}.
118    */
119   // Casting to any type is safe since there are no actual elements.
120   @SuppressWarnings("unchecked")
121   static <T> UnmodifiableListIterator<T> emptyListIterator() {
122     return (UnmodifiableListIterator<T>) EMPTY_LIST_ITERATOR;
123   }
124 
125   private static final Iterator<Object> EMPTY_MODIFIABLE_ITERATOR =
126       new Iterator<Object>() {
127         @Override public boolean hasNext() {
128           return false;
129         }
130 
131         @Override public Object next() {
132           throw new NoSuchElementException();
133         }
134 
135         @Override public void remove() {
136           checkRemove(false);
137         }
138       };
139 
140   /**
141    * Returns the empty {@code Iterator} that throws
142    * {@link IllegalStateException} instead of
143    * {@link UnsupportedOperationException} on a call to
144    * {@link Iterator#remove()}.
145    */
146   // Casting to any type is safe since there are no actual elements.
147   @SuppressWarnings("unchecked")
148   static <T> Iterator<T> emptyModifiableIterator() {
149     return (Iterator<T>) EMPTY_MODIFIABLE_ITERATOR;
150   }
151 
152   /** Returns an unmodifiable view of {@code iterator}. */
153   public static <T> UnmodifiableIterator<T> unmodifiableIterator(
154       final Iterator<T> iterator) {
155     checkNotNull(iterator);
156     if (iterator instanceof UnmodifiableIterator) {
157       return (UnmodifiableIterator<T>) iterator;
158     }
159     return new UnmodifiableIterator<T>() {
160       @Override
161       public boolean hasNext() {
162         return iterator.hasNext();
163       }
164       @Override
165       public T next() {
166         return iterator.next();
167       }
168     };
169   }
170 
171   /**
172    * Simply returns its argument.
173    *
174    * @deprecated no need to use this
175    * @since 10.0
176    */
177   @Deprecated public static <T> UnmodifiableIterator<T> unmodifiableIterator(
178       UnmodifiableIterator<T> iterator) {
179     return checkNotNull(iterator);
180   }
181 
182   /**
183    * Returns the number of elements remaining in {@code iterator}. The iterator
184    * will be left exhausted: its {@code hasNext()} method will return
185    * {@code false}.
186    */
187   public static int size(Iterator<?> iterator) {
188     int count = 0;
189     while (iterator.hasNext()) {
190       iterator.next();
191       count++;
192     }
193     return count;
194   }
195 
196   /**
197    * Returns {@code true} if {@code iterator} contains {@code element}.
198    */
199   public static boolean contains(Iterator<?> iterator, @Nullable Object element) {
200     return any(iterator, equalTo(element));
201   }
202 
203   /**
204    * Traverses an iterator and removes every element that belongs to the
205    * provided collection. The iterator will be left exhausted: its
206    * {@code hasNext()} method will return {@code false}.
207    *
208    * @param removeFrom the iterator to (potentially) remove elements from
209    * @param elementsToRemove the elements to remove
210    * @return {@code true} if any element was removed from {@code iterator}
211    */
212   public static boolean removeAll(
213       Iterator<?> removeFrom, Collection<?> elementsToRemove) {
214     return removeIf(removeFrom, in(elementsToRemove));
215   }
216 
217   /**
218    * Removes every element that satisfies the provided predicate from the
219    * iterator. The iterator will be left exhausted: its {@code hasNext()}
220    * method will return {@code false}.
221    *
222    * @param removeFrom the iterator to (potentially) remove elements from
223    * @param predicate a predicate that determines whether an element should
224    *     be removed
225    * @return {@code true} if any elements were removed from the iterator
226    * @since 2.0
227    */
228   public static <T> boolean removeIf(
229       Iterator<T> removeFrom, Predicate<? super T> predicate) {
230     checkNotNull(predicate);
231     boolean modified = false;
232     while (removeFrom.hasNext()) {
233       if (predicate.apply(removeFrom.next())) {
234         removeFrom.remove();
235         modified = true;
236       }
237     }
238     return modified;
239   }
240 
241   /**
242    * Traverses an iterator and removes every element that does not belong to the
243    * provided collection. The iterator will be left exhausted: its
244    * {@code hasNext()} method will return {@code false}.
245    *
246    * @param removeFrom the iterator to (potentially) remove elements from
247    * @param elementsToRetain the elements to retain
248    * @return {@code true} if any element was removed from {@code iterator}
249    */
250   public static boolean retainAll(
251       Iterator<?> removeFrom, Collection<?> elementsToRetain) {
252     return removeIf(removeFrom, not(in(elementsToRetain)));
253   }
254 
255   /**
256    * Determines whether two iterators contain equal elements in the same order.
257    * More specifically, this method returns {@code true} if {@code iterator1}
258    * and {@code iterator2} contain the same number of elements and every element
259    * of {@code iterator1} is equal to the corresponding element of
260    * {@code iterator2}.
261    *
262    * <p>Note that this will modify the supplied iterators, since they will have
263    * been advanced some number of elements forward.
264    */
265   public static boolean elementsEqual(
266       Iterator<?> iterator1, Iterator<?> iterator2) {
267     while (iterator1.hasNext()) {
268       if (!iterator2.hasNext()) {
269         return false;
270       }
271       Object o1 = iterator1.next();
272       Object o2 = iterator2.next();
273       if (!Objects.equal(o1, o2)) {
274         return false;
275       }
276     }
277     return !iterator2.hasNext();
278   }
279 
280   /**
281    * Returns a string representation of {@code iterator}, with the format
282    * {@code [e1, e2, ..., en]}. The iterator will be left exhausted: its
283    * {@code hasNext()} method will return {@code false}.
284    */
285   public static String toString(Iterator<?> iterator) {
286     return Collections2.STANDARD_JOINER
287         .appendTo(new StringBuilder().append('['), iterator)
288         .append(']')
289         .toString();
290   }
291 
292   /**
293    * Returns the single element contained in {@code iterator}.
294    *
295    * @throws NoSuchElementException if the iterator is empty
296    * @throws IllegalArgumentException if the iterator contains multiple
297    *     elements.  The state of the iterator is unspecified.
298    */
299   public static <T> T getOnlyElement(Iterator<T> iterator) {
300     T first = iterator.next();
301     if (!iterator.hasNext()) {
302       return first;
303     }
304 
305     StringBuilder sb = new StringBuilder();
306     sb.append("expected one element but was: <" + first);
307     for (int i = 0; i < 4 && iterator.hasNext(); i++) {
308       sb.append(", " + iterator.next());
309     }
310     if (iterator.hasNext()) {
311       sb.append(", ...");
312     }
313     sb.append('>');
314 
315     throw new IllegalArgumentException(sb.toString());
316   }
317 
318   /**
319    * Returns the single element contained in {@code iterator}, or {@code
320    * defaultValue} if the iterator is empty.
321    *
322    * @throws IllegalArgumentException if the iterator contains multiple
323    *     elements.  The state of the iterator is unspecified.
324    */
325   @Nullable
326   public static <T> T getOnlyElement(Iterator<? extends T> iterator, @Nullable T defaultValue) {
327     return iterator.hasNext() ? getOnlyElement(iterator) : defaultValue;
328   }
329 
330   /**
331    * Adds all elements in {@code iterator} to {@code collection}. The iterator
332    * will be left exhausted: its {@code hasNext()} method will return
333    * {@code false}.
334    *
335    * @return {@code true} if {@code collection} was modified as a result of this
336    *         operation
337    */
338   public static <T> boolean addAll(
339       Collection<T> addTo, Iterator<? extends T> iterator) {
340     checkNotNull(addTo);
341     checkNotNull(iterator);
342     boolean wasModified = false;
343     while (iterator.hasNext()) {
344       wasModified |= addTo.add(iterator.next());
345     }
346     return wasModified;
347   }
348 
349   /**
350    * Returns the number of elements in the specified iterator that equal the
351    * specified object. The iterator will be left exhausted: its
352    * {@code hasNext()} method will return {@code false}.
353    *
354    * @see Collections#frequency
355    */
356   public static int frequency(Iterator<?> iterator, @Nullable Object element) {
357     return size(filter(iterator, equalTo(element)));
358   }
359 
360   /**
361    * Returns an iterator that cycles indefinitely over the elements of {@code
362    * iterable}.
363    *
364    * <p>The returned iterator supports {@code remove()} if the provided iterator
365    * does. After {@code remove()} is called, subsequent cycles omit the removed
366    * element, which is no longer in {@code iterable}. The iterator's
367    * {@code hasNext()} method returns {@code true} until {@code iterable} is
368    * empty.
369    *
370    * <p><b>Warning:</b> Typical uses of the resulting iterator may produce an
371    * infinite loop. You should use an explicit {@code break} or be certain that
372    * you will eventually remove all the elements.
373    */
374   public static <T> Iterator<T> cycle(final Iterable<T> iterable) {
375     checkNotNull(iterable);
376     return new Iterator<T>() {
377       Iterator<T> iterator = emptyIterator();
378       Iterator<T> removeFrom;
379 
380       @Override
381       public boolean hasNext() {
382         if (!iterator.hasNext()) {
383           iterator = iterable.iterator();
384         }
385         return iterator.hasNext();
386       }
387       @Override
388       public T next() {
389         if (!hasNext()) {
390           throw new NoSuchElementException();
391         }
392         removeFrom = iterator;
393         return iterator.next();
394       }
395       @Override
396       public void remove() {
397         checkRemove(removeFrom != null);
398         removeFrom.remove();
399         removeFrom = null;
400       }
401     };
402   }
403 
404   /**
405    * Returns an iterator that cycles indefinitely over the provided elements.
406    *
407    * <p>The returned iterator supports {@code remove()}. After {@code remove()}
408    * is called, subsequent cycles omit the removed
409    * element, but {@code elements} does not change. The iterator's
410    * {@code hasNext()} method returns {@code true} until all of the original
411    * elements have been removed.
412    *
413    * <p><b>Warning:</b> Typical uses of the resulting iterator may produce an
414    * infinite loop. You should use an explicit {@code break} or be certain that
415    * you will eventually remove all the elements.
416    */
417   public static <T> Iterator<T> cycle(T... elements) {
418     return cycle(Lists.newArrayList(elements));
419   }
420 
421   /**
422    * Combines two iterators into a single iterator. The returned iterator
423    * iterates across the elements in {@code a}, followed by the elements in
424    * {@code b}. The source iterators are not polled until necessary.
425    *
426    * <p>The returned iterator supports {@code remove()} when the corresponding
427    * input iterator supports it.
428    *
429    * <p><b>Note:</b> the current implementation is not suitable for nested
430    * concatenated iterators, i.e. the following should be avoided when in a loop:
431    * {@code iterator = Iterators.concat(iterator, suffix);}, since iteration over the
432    * resulting iterator has a cubic complexity to the depth of the nesting.
433    */
434   public static <T> Iterator<T> concat(Iterator<? extends T> a,
435       Iterator<? extends T> b) {
436     return concat(ImmutableList.of(a, b).iterator());
437   }
438 
439   /**
440    * Combines three iterators into a single iterator. The returned iterator
441    * iterates across the elements in {@code a}, followed by the elements in
442    * {@code b}, followed by the elements in {@code c}. The source iterators
443    * are not polled until necessary.
444    *
445    * <p>The returned iterator supports {@code remove()} when the corresponding
446    * input iterator supports it.
447    *
448    * <p><b>Note:</b> the current implementation is not suitable for nested
449    * concatenated iterators, i.e. the following should be avoided when in a loop:
450    * {@code iterator = Iterators.concat(iterator, suffix);}, since iteration over the
451    * resulting iterator has a cubic complexity to the depth of the nesting.
452    */
453   public static <T> Iterator<T> concat(Iterator<? extends T> a,
454       Iterator<? extends T> b, Iterator<? extends T> c) {
455     return concat(ImmutableList.of(a, b, c).iterator());
456   }
457 
458   /**
459    * Combines four iterators into a single iterator. The returned iterator
460    * iterates across the elements in {@code a}, followed by the elements in
461    * {@code b}, followed by the elements in {@code c}, followed by the elements
462    * in {@code d}. The source iterators are not polled until necessary.
463    *
464    * <p>The returned iterator supports {@code remove()} when the corresponding
465    * input iterator supports it.
466    *
467    * <p><b>Note:</b> the current implementation is not suitable for nested
468    * concatenated iterators, i.e. the following should be avoided when in a loop:
469    * {@code iterator = Iterators.concat(iterator, suffix);}, since iteration over the
470    * resulting iterator has a cubic complexity to the depth of the nesting.
471    */
472   public static <T> Iterator<T> concat(Iterator<? extends T> a,
473       Iterator<? extends T> b, Iterator<? extends T> c,
474       Iterator<? extends T> d) {
475     return concat(ImmutableList.of(a, b, c, d).iterator());
476   }
477 
478   /**
479    * Combines multiple iterators into a single iterator. The returned iterator
480    * iterates across the elements of each iterator in {@code inputs}. The input
481    * iterators are not polled until necessary.
482    *
483    * <p>The returned iterator supports {@code remove()} when the corresponding
484    * input iterator supports it.
485    *
486    * <p><b>Note:</b> the current implementation is not suitable for nested
487    * concatenated iterators, i.e. the following should be avoided when in a loop:
488    * {@code iterator = Iterators.concat(iterator, suffix);}, since iteration over the
489    * resulting iterator has a cubic complexity to the depth of the nesting.
490    *
491    * @throws NullPointerException if any of the provided iterators is null
492    */
493   public static <T> Iterator<T> concat(Iterator<? extends T>... inputs) {
494     return concat(ImmutableList.copyOf(inputs).iterator());
495   }
496 
497   /**
498    * Combines multiple iterators into a single iterator. The returned iterator
499    * iterates across the elements of each iterator in {@code inputs}. The input
500    * iterators are not polled until necessary.
501    *
502    * <p>The returned iterator supports {@code remove()} when the corresponding
503    * input iterator supports it. The methods of the returned iterator may throw
504    * {@code NullPointerException} if any of the input iterators is null.
505    *
506    * <p><b>Note:</b> the current implementation is not suitable for nested
507    * concatenated iterators, i.e. the following should be avoided when in a loop:
508    * {@code iterator = Iterators.concat(iterator, suffix);}, since iteration over the
509    * resulting iterator has a cubic complexity to the depth of the nesting.
510    */
511   public static <T> Iterator<T> concat(
512       final Iterator<? extends Iterator<? extends T>> inputs) {
513     checkNotNull(inputs);
514     return new Iterator<T>() {
515       Iterator<? extends T> current = emptyIterator();
516       Iterator<? extends T> removeFrom;
517 
518       @Override
519       public boolean hasNext() {
520         // http://code.google.com/p/google-collections/issues/detail?id=151
521         // current.hasNext() might be relatively expensive, worth minimizing.
522         boolean currentHasNext;
523         // checkNotNull eager for GWT
524         // note: it must be here & not where 'current' is assigned,
525         // because otherwise we'll have called inputs.next() before throwing
526         // the first NPE, and the next time around we'll call inputs.next()
527         // again, incorrectly moving beyond the error.
528         while (!(currentHasNext = checkNotNull(current).hasNext())
529             && inputs.hasNext()) {
530           current = inputs.next();
531         }
532         return currentHasNext;
533       }
534       @Override
535       public T next() {
536         if (!hasNext()) {
537           throw new NoSuchElementException();
538         }
539         removeFrom = current;
540         return current.next();
541       }
542       @Override
543       public void remove() {
544         checkRemove(removeFrom != null);
545         removeFrom.remove();
546         removeFrom = null;
547       }
548     };
549   }
550 
551   /**
552    * Divides an iterator into unmodifiable sublists of the given size (the final
553    * list may be smaller). For example, partitioning an iterator containing
554    * {@code [a, b, c, d, e]} with a partition size of 3 yields {@code
555    * [[a, b, c], [d, e]]} -- an outer iterator containing two inner lists of
556    * three and two elements, all in the original order.
557    *
558    * <p>The returned lists implement {@link java.util.RandomAccess}.
559    *
560    * @param iterator the iterator to return a partitioned view of
561    * @param size the desired size of each partition (the last may be smaller)
562    * @return an iterator of immutable lists containing the elements of {@code
563    *     iterator} divided into partitions
564    * @throws IllegalArgumentException if {@code size} is nonpositive
565    */
566   public static <T> UnmodifiableIterator<List<T>> partition(
567       Iterator<T> iterator, int size) {
568     return partitionImpl(iterator, size, false);
569   }
570 
571   /**
572    * Divides an iterator into unmodifiable sublists of the given size, padding
573    * the final iterator with null values if necessary. For example, partitioning
574    * an iterator containing {@code [a, b, c, d, e]} with a partition size of 3
575    * yields {@code [[a, b, c], [d, e, null]]} -- an outer iterator containing
576    * two inner lists of three elements each, all in the original order.
577    *
578    * <p>The returned lists implement {@link java.util.RandomAccess}.
579    *
580    * @param iterator the iterator to return a partitioned view of
581    * @param size the desired size of each partition
582    * @return an iterator of immutable lists containing the elements of {@code
583    *     iterator} divided into partitions (the final iterable may have
584    *     trailing null elements)
585    * @throws IllegalArgumentException if {@code size} is nonpositive
586    */
587   public static <T> UnmodifiableIterator<List<T>> paddedPartition(
588       Iterator<T> iterator, int size) {
589     return partitionImpl(iterator, size, true);
590   }
591 
592   private static <T> UnmodifiableIterator<List<T>> partitionImpl(
593       final Iterator<T> iterator, final int size, final boolean pad) {
594     checkNotNull(iterator);
595     checkArgument(size > 0);
596     return new UnmodifiableIterator<List<T>>() {
597       @Override
598       public boolean hasNext() {
599         return iterator.hasNext();
600       }
601       @Override
602       public List<T> next() {
603         if (!hasNext()) {
604           throw new NoSuchElementException();
605         }
606         Object[] array = new Object[size];
607         int count = 0;
608         for (; count < size && iterator.hasNext(); count++) {
609           array[count] = iterator.next();
610         }
611         for (int i = count; i < size; i++) {
612           array[i] = null; // for GWT
613         }
614 
615         @SuppressWarnings("unchecked") // we only put Ts in it
616         List<T> list = Collections.unmodifiableList(
617             (List<T>) Arrays.asList(array));
618         return (pad || count == size) ? list : list.subList(0, count);
619       }
620     };
621   }
622 
623   /**
624    * Returns the elements of {@code unfiltered} that satisfy a predicate.
625    */
626   public static <T> UnmodifiableIterator<T> filter(
627       final Iterator<T> unfiltered, final Predicate<? super T> predicate) {
628     checkNotNull(unfiltered);
629     checkNotNull(predicate);
630     return new AbstractIterator<T>() {
631       @Override protected T computeNext() {
632         while (unfiltered.hasNext()) {
633           T element = unfiltered.next();
634           if (predicate.apply(element)) {
635             return element;
636           }
637         }
638         return endOfData();
639       }
640     };
641   }
642 
643   /**
644    * Returns {@code true} if one or more elements returned by {@code iterator}
645    * satisfy the given predicate.
646    */
647   public static <T> boolean any(
648       Iterator<T> iterator, Predicate<? super T> predicate) {
649     return indexOf(iterator, predicate) != -1;
650   }
651 
652   /**
653    * Returns {@code true} if every element returned by {@code iterator}
654    * satisfies the given predicate. If {@code iterator} is empty, {@code true}
655    * is returned.
656    */
657   public static <T> boolean all(
658       Iterator<T> iterator, Predicate<? super T> predicate) {
659     checkNotNull(predicate);
660     while (iterator.hasNext()) {
661       T element = iterator.next();
662       if (!predicate.apply(element)) {
663         return false;
664       }
665     }
666     return true;
667   }
668 
669   /**
670    * Returns the first element in {@code iterator} that satisfies the given
671    * predicate; use this method only when such an element is known to exist. If
672    * no such element is found, the iterator will be left exhausted: its {@code
673    * hasNext()} method will return {@code false}. If it is possible that
674    * <i>no</i> element will match, use {@link #tryFind} or {@link
675    * #find(Iterator, Predicate, Object)} instead.
676    *
677    * @throws NoSuchElementException if no element in {@code iterator} matches
678    *     the given predicate
679    */
680   public static <T> T find(
681       Iterator<T> iterator, Predicate<? super T> predicate) {
682     return filter(iterator, predicate).next();
683   }
684 
685   /**
686    * Returns the first element in {@code iterator} that satisfies the given
687    * predicate. If no such element is found, {@code defaultValue} will be
688    * returned from this method and the iterator will be left exhausted: its
689    * {@code hasNext()} method will return {@code false}. Note that this can
690    * usually be handled more naturally using {@code
691    * tryFind(iterator, predicate).or(defaultValue)}.
692    *
693    * @since 7.0
694    */
695   @Nullable
696   public static <T> T find(Iterator<? extends T> iterator, Predicate<? super T> predicate,
697       @Nullable T defaultValue) {
698     return getNext(filter(iterator, predicate), defaultValue);
699   }
700 
701   /**
702    * Returns an {@link Optional} containing the first element in {@code
703    * iterator} that satisfies the given predicate, if such an element exists. If
704    * no such element is found, an empty {@link Optional} will be returned from
705    * this method and the iterator will be left exhausted: its {@code
706    * hasNext()} method will return {@code false}.
707    *
708    * <p><b>Warning:</b> avoid using a {@code predicate} that matches {@code
709    * null}. If {@code null} is matched in {@code iterator}, a
710    * NullPointerException will be thrown.
711    *
712    * @since 11.0
713    */
714   public static <T> Optional<T> tryFind(
715       Iterator<T> iterator, Predicate<? super T> predicate) {
716     UnmodifiableIterator<T> filteredIterator = filter(iterator, predicate);
717     return filteredIterator.hasNext()
718         ? Optional.of(filteredIterator.next())
719         : Optional.<T>absent();
720   }
721 
722   /**
723    * Returns the index in {@code iterator} of the first element that satisfies
724    * the provided {@code predicate}, or {@code -1} if the Iterator has no such
725    * elements.
726    *
727    * <p>More formally, returns the lowest index {@code i} such that
728    * {@code predicate.apply(Iterators.get(iterator, i))} returns {@code true},
729    * or {@code -1} if there is no such index.
730    *
731    * <p>If -1 is returned, the iterator will be left exhausted: its
732    * {@code hasNext()} method will return {@code false}.  Otherwise,
733    * the iterator will be set to the element which satisfies the
734    * {@code predicate}.
735    *
736    * @since 2.0
737    */
738   public static <T> int indexOf(
739       Iterator<T> iterator, Predicate<? super T> predicate) {
740     checkNotNull(predicate, "predicate");
741     for (int i = 0; iterator.hasNext(); i++) {
742       T current = iterator.next();
743       if (predicate.apply(current)) {
744         return i;
745       }
746     }
747     return -1;
748   }
749 
750   /**
751    * Returns an iterator that applies {@code function} to each element of {@code
752    * fromIterator}.
753    *
754    * <p>The returned iterator supports {@code remove()} if the provided iterator
755    * does. After a successful {@code remove()} call, {@code fromIterator} no
756    * longer contains the corresponding element.
757    */
758   public static <F, T> Iterator<T> transform(final Iterator<F> fromIterator,
759       final Function<? super F, ? extends T> function) {
760     checkNotNull(function);
761     return new TransformedIterator<F, T>(fromIterator) {
762       @Override
763       T transform(F from) {
764         return function.apply(from);
765       }
766     };
767   }
768 
769   /**
770    * Advances {@code iterator} {@code position + 1} times, returning the
771    * element at the {@code position}th position.
772    *
773    * @param position position of the element to return
774    * @return the element at the specified position in {@code iterator}
775    * @throws IndexOutOfBoundsException if {@code position} is negative or
776    *     greater than or equal to the number of elements remaining in
777    *     {@code iterator}
778    */
779   public static <T> T get(Iterator<T> iterator, int position) {
780     checkNonnegative(position);
781     int skipped = advance(iterator, position);
782     if (!iterator.hasNext()) {
783       throw new IndexOutOfBoundsException("position (" + position
784           + ") must be less than the number of elements that remained ("
785           + skipped + ")");
786     }
787     return iterator.next();
788   }
789 
790   static void checkNonnegative(int position) {
791     if (position < 0) {
792       throw new IndexOutOfBoundsException("position (" + position
793           + ") must not be negative");
794     }
795   }
796 
797   /**
798    * Advances {@code iterator} {@code position + 1} times, returning the
799    * element at the {@code position}th position or {@code defaultValue}
800    * otherwise.
801    *
802    * @param position position of the element to return
803    * @param defaultValue the default value to return if the iterator is empty
804    *     or if {@code position} is greater than the number of elements
805    *     remaining in {@code iterator}
806    * @return the element at the specified position in {@code iterator} or
807    *     {@code defaultValue} if {@code iterator} produces fewer than
808    *     {@code position + 1} elements.
809    * @throws IndexOutOfBoundsException if {@code position} is negative
810    * @since 4.0
811    */
812   @Nullable
813   public static <T> T get(Iterator<? extends T> iterator, int position, @Nullable T defaultValue) {
814     checkNonnegative(position);
815     advance(iterator, position);
816     return getNext(iterator, defaultValue);
817   }
818 
819   /**
820    * Returns the next element in {@code iterator} or {@code defaultValue} if
821    * the iterator is empty.  The {@link Iterables} analog to this method is
822    * {@link Iterables#getFirst}.
823    *
824    * @param defaultValue the default value to return if the iterator is empty
825    * @return the next element of {@code iterator} or the default value
826    * @since 7.0
827    */
828   @Nullable
829   public static <T> T getNext(Iterator<? extends T> iterator, @Nullable T defaultValue) {
830     return iterator.hasNext() ? iterator.next() : defaultValue;
831   }
832 
833   /**
834    * Advances {@code iterator} to the end, returning the last element.
835    *
836    * @return the last element of {@code iterator}
837    * @throws NoSuchElementException if the iterator is empty
838    */
839   public static <T> T getLast(Iterator<T> iterator) {
840     while (true) {
841       T current = iterator.next();
842       if (!iterator.hasNext()) {
843         return current;
844       }
845     }
846   }
847 
848   /**
849    * Advances {@code iterator} to the end, returning the last element or
850    * {@code defaultValue} if the iterator is empty.
851    *
852    * @param defaultValue the default value to return if the iterator is empty
853    * @return the last element of {@code iterator}
854    * @since 3.0
855    */
856   @Nullable
857   public static <T> T getLast(Iterator<? extends T> iterator, @Nullable T defaultValue) {
858     return iterator.hasNext() ? getLast(iterator) : defaultValue;
859   }
860 
861   /**
862    * Calls {@code next()} on {@code iterator}, either {@code numberToAdvance} times
863    * or until {@code hasNext()} returns {@code false}, whichever comes first.
864    *
865    * @return the number of elements the iterator was advanced
866    * @since 13.0 (since 3.0 as {@code Iterators.skip})
867    */
868   public static int advance(Iterator<?> iterator, int numberToAdvance) {
869     checkNotNull(iterator);
870     checkArgument(numberToAdvance >= 0, "numberToAdvance must be nonnegative");
871 
872     int i;
873     for (i = 0; i < numberToAdvance && iterator.hasNext(); i++) {
874       iterator.next();
875     }
876     return i;
877   }
878 
879   /**
880    * Creates an iterator returning the first {@code limitSize} elements of the
881    * given iterator. If the original iterator does not contain that many
882    * elements, the returned iterator will have the same behavior as the original
883    * iterator. The returned iterator supports {@code remove()} if the original
884    * iterator does.
885    *
886    * @param iterator the iterator to limit
887    * @param limitSize the maximum number of elements in the returned iterator
888    * @throws IllegalArgumentException if {@code limitSize} is negative
889    * @since 3.0
890    */
891   public static <T> Iterator<T> limit(
892       final Iterator<T> iterator, final int limitSize) {
893     checkNotNull(iterator);
894     checkArgument(limitSize >= 0, "limit is negative");
895     return new Iterator<T>() {
896       private int count;
897 
898       @Override
899       public boolean hasNext() {
900         return count < limitSize && iterator.hasNext();
901       }
902 
903       @Override
904       public T next() {
905         if (!hasNext()) {
906           throw new NoSuchElementException();
907         }
908         count++;
909         return iterator.next();
910       }
911 
912       @Override
913       public void remove() {
914         iterator.remove();
915       }
916     };
917   }
918 
919   /**
920    * Returns a view of the supplied {@code iterator} that removes each element
921    * from the supplied {@code iterator} as it is returned.
922    *
923    * <p>The provided iterator must support {@link Iterator#remove()} or
924    * else the returned iterator will fail on the first call to {@code
925    * next}.
926    *
927    * @param iterator the iterator to remove and return elements from
928    * @return an iterator that removes and returns elements from the
929    *     supplied iterator
930    * @since 2.0
931    */
932   public static <T> Iterator<T> consumingIterator(final Iterator<T> iterator) {
933     checkNotNull(iterator);
934     return new UnmodifiableIterator<T>() {
935       @Override
936       public boolean hasNext() {
937         return iterator.hasNext();
938       }
939 
940       @Override
941       public T next() {
942         T next = iterator.next();
943         iterator.remove();
944         return next;
945       }
946 
947       @Override
948       public String toString() {
949         return "Iterators.consumingIterator(...)";
950       }
951     };
952   }
953 
954   /**
955    * Deletes and returns the next value from the iterator, or returns
956    * {@code null} if there is no such value.
957    */
958   @Nullable
959   static <T> T pollNext(Iterator<T> iterator) {
960     if (iterator.hasNext()) {
961       T result = iterator.next();
962       iterator.remove();
963       return result;
964     } else {
965       return null;
966     }
967   }
968 
969   // Methods only in Iterators, not in Iterables
970 
971   /**
972    * Clears the iterator using its remove method.
973    */
974   static void clear(Iterator<?> iterator) {
975     checkNotNull(iterator);
976     while (iterator.hasNext()) {
977       iterator.next();
978       iterator.remove();
979     }
980   }
981 
982   /**
983    * Returns an iterator containing the elements of {@code array} in order. The
984    * returned iterator is a view of the array; subsequent changes to the array
985    * will be reflected in the iterator.
986    *
987    * <p><b>Note:</b> It is often preferable to represent your data using a
988    * collection type, for example using {@link Arrays#asList(Object[])}, making
989    * this method unnecessary.
990    *
991    * <p>The {@code Iterable} equivalent of this method is either {@link
992    * Arrays#asList(Object[])}, {@link ImmutableList#copyOf(Object[])}},
993    * or {@link ImmutableList#of}.
994    */
995   public static <T> UnmodifiableIterator<T> forArray(final T... array) {
996     return forArray(array, 0, array.length, 0);
997   }
998 
999   /**
1000    * Returns a list iterator containing the elements in the specified range of
1001    * {@code array} in order, starting at the specified index.
1002    *
1003    * <p>The {@code Iterable} equivalent of this method is {@code
1004    * Arrays.asList(array).subList(offset, offset + length).listIterator(index)}.
1005    */
1006   static <T> UnmodifiableListIterator<T> forArray(
1007       final T[] array, final int offset, int length, int index) {
1008     checkArgument(length >= 0);
1009     int end = offset + length;
1010 
1011     // Technically we should give a slightly more descriptive error on overflow
1012     Preconditions.checkPositionIndexes(offset, end, array.length);
1013     Preconditions.checkPositionIndex(index, length);
1014     if (length == 0) {
1015       return emptyListIterator();
1016     }
1017 
1018     /*
1019      * We can't use call the two-arg constructor with arguments (offset, end)
1020      * because the returned Iterator is a ListIterator that may be moved back
1021      * past the beginning of the iteration.
1022      */
1023     return new AbstractIndexedListIterator<T>(length, index) {
1024       @Override protected T get(int index) {
1025         return array[offset + index];
1026       }
1027     };
1028   }
1029 
1030   /**
1031    * Returns an iterator containing only {@code value}.
1032    *
1033    * <p>The {@link Iterable} equivalent of this method is {@link
1034    * Collections#singleton}.
1035    */
1036   public static <T> UnmodifiableIterator<T> singletonIterator(
1037       @Nullable final T value) {
1038     return new UnmodifiableIterator<T>() {
1039       boolean done;
1040       @Override
1041       public boolean hasNext() {
1042         return !done;
1043       }
1044       @Override
1045       public T next() {
1046         if (done) {
1047           throw new NoSuchElementException();
1048         }
1049         done = true;
1050         return value;
1051       }
1052     };
1053   }
1054 
1055   /**
1056    * Adapts an {@code Enumeration} to the {@code Iterator} interface.
1057    *
1058    * <p>This method has no equivalent in {@link Iterables} because viewing an
1059    * {@code Enumeration} as an {@code Iterable} is impossible. However, the
1060    * contents can be <i>copied</i> into a collection using {@link
1061    * Collections#list}.
1062    */
1063   public static <T> UnmodifiableIterator<T> forEnumeration(
1064       final Enumeration<T> enumeration) {
1065     checkNotNull(enumeration);
1066     return new UnmodifiableIterator<T>() {
1067       @Override
1068       public boolean hasNext() {
1069         return enumeration.hasMoreElements();
1070       }
1071       @Override
1072       public T next() {
1073         return enumeration.nextElement();
1074       }
1075     };
1076   }
1077 
1078   /**
1079    * Adapts an {@code Iterator} to the {@code Enumeration} interface.
1080    *
1081    * <p>The {@code Iterable} equivalent of this method is either {@link
1082    * Collections#enumeration} (if you have a {@link Collection}), or
1083    * {@code Iterators.asEnumeration(collection.iterator())}.
1084    */
1085   public static <T> Enumeration<T> asEnumeration(final Iterator<T> iterator) {
1086     checkNotNull(iterator);
1087     return new Enumeration<T>() {
1088       @Override
1089       public boolean hasMoreElements() {
1090         return iterator.hasNext();
1091       }
1092       @Override
1093       public T nextElement() {
1094         return iterator.next();
1095       }
1096     };
1097   }
1098 
1099   /**
1100    * Implementation of PeekingIterator that avoids peeking unless necessary.
1101    */
1102   private static class PeekingImpl<E> implements PeekingIterator<E> {
1103 
1104     private final Iterator<? extends E> iterator;
1105     private boolean hasPeeked;
1106     private E peekedElement;
1107 
1108     public PeekingImpl(Iterator<? extends E> iterator) {
1109       this.iterator = checkNotNull(iterator);
1110     }
1111 
1112     @Override
1113     public boolean hasNext() {
1114       return hasPeeked || iterator.hasNext();
1115     }
1116 
1117     @Override
1118     public E next() {
1119       if (!hasPeeked) {
1120         return iterator.next();
1121       }
1122       E result = peekedElement;
1123       hasPeeked = false;
1124       peekedElement = null;
1125       return result;
1126     }
1127 
1128     @Override
1129     public void remove() {
1130       checkState(!hasPeeked, "Can't remove after you've peeked at next");
1131       iterator.remove();
1132     }
1133 
1134     @Override
1135     public E peek() {
1136       if (!hasPeeked) {
1137         peekedElement = iterator.next();
1138         hasPeeked = true;
1139       }
1140       return peekedElement;
1141     }
1142   }
1143 
1144   /**
1145    * Returns a {@code PeekingIterator} backed by the given iterator.
1146    *
1147    * <p>Calls to the {@code peek} method with no intervening calls to {@code
1148    * next} do not affect the iteration, and hence return the same object each
1149    * time. A subsequent call to {@code next} is guaranteed to return the same
1150    * object again. For example: <pre>   {@code
1151    *
1152    *   PeekingIterator<String> peekingIterator =
1153    *       Iterators.peekingIterator(Iterators.forArray("a", "b"));
1154    *   String a1 = peekingIterator.peek(); // returns "a"
1155    *   String a2 = peekingIterator.peek(); // also returns "a"
1156    *   String a3 = peekingIterator.next(); // also returns "a"}</pre>
1157    *
1158    * <p>Any structural changes to the underlying iteration (aside from those
1159    * performed by the iterator's own {@link PeekingIterator#remove()} method)
1160    * will leave the iterator in an undefined state.
1161    *
1162    * <p>The returned iterator does not support removal after peeking, as
1163    * explained by {@link PeekingIterator#remove()}.
1164    *
1165    * <p>Note: If the given iterator is already a {@code PeekingIterator},
1166    * it <i>might</i> be returned to the caller, although this is neither
1167    * guaranteed to occur nor required to be consistent.  For example, this
1168    * method <i>might</i> choose to pass through recognized implementations of
1169    * {@code PeekingIterator} when the behavior of the implementation is
1170    * known to meet the contract guaranteed by this method.
1171    *
1172    * <p>There is no {@link Iterable} equivalent to this method, so use this
1173    * method to wrap each individual iterator as it is generated.
1174    *
1175    * @param iterator the backing iterator. The {@link PeekingIterator} assumes
1176    *     ownership of this iterator, so users should cease making direct calls
1177    *     to it after calling this method.
1178    * @return a peeking iterator backed by that iterator. Apart from the
1179    *     additional {@link PeekingIterator#peek()} method, this iterator behaves
1180    *     exactly the same as {@code iterator}.
1181    */
1182   public static <T> PeekingIterator<T> peekingIterator(
1183       Iterator<? extends T> iterator) {
1184     if (iterator instanceof PeekingImpl) {
1185       // Safe to cast <? extends T> to <T> because PeekingImpl only uses T
1186       // covariantly (and cannot be subclassed to add non-covariant uses).
1187       @SuppressWarnings("unchecked")
1188       PeekingImpl<T> peeking = (PeekingImpl<T>) iterator;
1189       return peeking;
1190     }
1191     return new PeekingImpl<T>(iterator);
1192   }
1193 
1194   /**
1195    * Simply returns its argument.
1196    *
1197    * @deprecated no need to use this
1198    * @since 10.0
1199    */
1200   @Deprecated public static <T> PeekingIterator<T> peekingIterator(
1201       PeekingIterator<T> iterator) {
1202     return checkNotNull(iterator);
1203   }
1204 
1205   /**
1206    * Returns an iterator over the merged contents of all given
1207    * {@code iterators}, traversing every element of the input iterators.
1208    * Equivalent entries will not be de-duplicated.
1209    *
1210    * <p>Callers must ensure that the source {@code iterators} are in
1211    * non-descending order as this method does not sort its input.
1212    *
1213    * <p>For any equivalent elements across all {@code iterators}, it is
1214    * undefined which element is returned first.
1215    *
1216    * @since 11.0
1217    */
1218   @Beta
1219   public static <T> UnmodifiableIterator<T> mergeSorted(
1220       Iterable<? extends Iterator<? extends T>> iterators,
1221       Comparator<? super T> comparator) {
1222     checkNotNull(iterators, "iterators");
1223     checkNotNull(comparator, "comparator");
1224 
1225     return new MergingIterator<T>(iterators, comparator);
1226   }
1227 
1228   /**
1229    * An iterator that performs a lazy N-way merge, calculating the next value
1230    * each time the iterator is polled. This amortizes the sorting cost over the
1231    * iteration and requires less memory than sorting all elements at once.
1232    *
1233    * <p>Retrieving a single element takes approximately O(log(M)) time, where M
1234    * is the number of iterators. (Retrieving all elements takes approximately
1235    * O(N*log(M)) time, where N is the total number of elements.)
1236    */
1237   private static class MergingIterator<T> extends UnmodifiableIterator<T> {
1238     final Queue<PeekingIterator<T>> queue;
1239 
1240     public MergingIterator(Iterable<? extends Iterator<? extends T>> iterators,
1241         final Comparator<? super T> itemComparator) {
1242       // A comparator that's used by the heap, allowing the heap
1243       // to be sorted based on the top of each iterator.
1244       Comparator<PeekingIterator<T>> heapComparator =
1245           new Comparator<PeekingIterator<T>>() {
1246             @Override
1247             public int compare(PeekingIterator<T> o1, PeekingIterator<T> o2) {
1248               return itemComparator.compare(o1.peek(), o2.peek());
1249             }
1250           };
1251 
1252       queue = new PriorityQueue<PeekingIterator<T>>(2, heapComparator);
1253 
1254       for (Iterator<? extends T> iterator : iterators) {
1255         if (iterator.hasNext()) {
1256           queue.add(Iterators.peekingIterator(iterator));
1257         }
1258       }
1259     }
1260 
1261     @Override
1262     public boolean hasNext() {
1263       return !queue.isEmpty();
1264     }
1265 
1266     @Override
1267     public T next() {
1268       PeekingIterator<T> nextIter = queue.remove();
1269       T next = nextIter.next();
1270       if (nextIter.hasNext()) {
1271         queue.add(nextIter);
1272       }
1273       return next;
1274     }
1275   }
1276 
1277   /**
1278    * Used to avoid http://bugs.sun.com/view_bug.do?bug_id=6558557
1279    */
1280   static <T> ListIterator<T> cast(Iterator<T> iterator) {
1281     return (ListIterator<T>) iterator;
1282   }
1283 }